package com.shouxue.cusradiobutton;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class CusRadioButton extends FrameLayout implements RadioGroup.OnCheckedChangeListener {
    private RadioGroup rg;
    private int mTextColor = Color.BLACK;
    private int mTextSelectColor = Color.RED;
    private int mDividerPadding = 0;
    private int mDividerColor = Color.GRAY;
    private Drawable mDividerDrawable = null;
    private float mTextSize = 20f;
    private int radioGroupBackground = R.drawable.bg_rg;
    private int radioButtonBackground = R.drawable.bg_select_center;
    private CustomRadioButtonSelect customRadioButtonSelect;
    private CustomRadioButtonFocus customRadioButtonFocus;
    private int select = -1;
    private List<String> itemCount = new ArrayList<>();
    private List<String> contentDescriptions = new ArrayList<>();
    private List<RadioButton> radioButtons = new ArrayList<>();
    RadioGroup.OnCheckedChangeListener onCheckedChangeListener;
    private boolean isSelectThreeStyle = false;
    private int leftSelectBg = R.drawable.bg_select_left;
    private int centerSelectBg = R.drawable.bg_select_center;
    private int rightSelectBg = R.drawable.bg_select_right;
    private boolean hasImgRadioButton = false;
    private int radioButtonSelectImg = R.drawable.car_select;
    private int radioButtonImg = R.drawable.car_normal;


    public CusRadioButton(@NonNull Context context) {
        this(context,null);
    }

    public CusRadioButton(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public CusRadioButton(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        getAttr(context, attrs, defStyleAttr);
        initView(context);
    }

    @SuppressLint("ResourceType")
    private void getAttr(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CusRadioButton, defStyleAttr, 0);
        int count = ta.getIndexCount();
        itemCount.clear();
        contentDescriptions.clear();
        for (int i = 0; i < count; i++) {
            int index = ta.getIndex(i);
            if (index == R.styleable.CusRadioButton_radioButtonSelect){
                select = ta.getInt(index,-1);
            }else if (index == R.styleable.CusRadioButton_radioTextColor){
                mTextColor = ta.getColor(index,Color.BLACK);
            }else if (index == R.styleable.CusRadioButton_radioSelectTextColor){
                mTextSelectColor = ta.getColor(index,Color.RED);
            }else if (index == R.styleable.CusRadioButton_radioTextSize){
                mTextSize = ta.getDimension(index,15f);
            }else if (index == R.styleable.CusRadioButton_radioDividerPadding){
                mDividerPadding = (int) ta.getDimension(index,0f);
            }else if (index == R.styleable.CusRadioButton_radioDividerColor){
                mDividerColor = ta.getColor(index,Color.BLACK);
            }else if (index == R.styleable.CusRadioButton_radioGroupBackground){
                radioGroupBackground = ta.getResourceId(index,R.drawable.bg_rg);
            }else if (index == R.styleable.CusRadioButton_radioButtonBackground){
                radioButtonBackground = ta.getResourceId(index,R.drawable.bg_select_center);
            }else if (index == R.styleable.CusRadioButton_radioButtonText1
                    || index == R.styleable.CusRadioButton_radioButtonText2
                    || index == R.styleable.CusRadioButton_radioButtonText3
                    || index == R.styleable.CusRadioButton_radioButtonText4
                    || index == R.styleable.CusRadioButton_radioButtonText5
                    || index == R.styleable.CusRadioButton_radioButtonText6){
                itemCount.add(ta.getString(index));
            }else if (index == R.styleable.CusRadioButton_contentDescriptionText1
                    || index == R.styleable.CusRadioButton_contentDescriptionText2
                    || index == R.styleable.CusRadioButton_contentDescriptionText3
                    || index == R.styleable.CusRadioButton_contentDescriptionText4
                    || index == R.styleable.CusRadioButton_contentDescriptionText5
                    || index == R.styleable.CusRadioButton_contentDescriptionText6){
                contentDescriptions.add(ta.getString(index));
            }else if (index == R.styleable.CusRadioButton_isRadioButtonBgThreeStyle){
                isSelectThreeStyle = ta.getBoolean(index,false);
            }else if (index == R.styleable.CusRadioButton_leftRadioButtonBg){
                leftSelectBg = ta.getResourceId(index,R.drawable.bg_select_left);
            }else if (index == R.styleable.CusRadioButton_centerRadioButtonBg){
                centerSelectBg = ta.getResourceId(index,R.drawable.bg_select_center);
            }else if (index == R.styleable.CusRadioButton_rightRadioButtonBg){
                rightSelectBg = ta.getResourceId(index,R.drawable.bg_select_right);
            }else if (index == R.styleable.CusRadioButton_hasImgTopRadioButton){
                hasImgRadioButton = ta.getBoolean(index,false);
            }else if (index == R.styleable.CusRadioButton_topSelectImgTopRadioButton){
                radioButtonSelectImg = ta.getResourceId(index,R.drawable.car_select);
            }else if (index == R.styleable.CusRadioButton_topImgTopRadioButton){
                radioButtonImg = ta.getResourceId(index,R.drawable.car_normal);
            }
        }
        ta.recycle();
    }
    public void setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener checkedChangeListener) {
        this.onCheckedChangeListener = checkedChangeListener;
    }

    @SuppressLint("ResourceType")
    private void initView(Context context) {
        radioButtons.clear();
        rg = new RadioGroup(context);
        rg.setId(getId());
        rg.setBackgroundResource(radioGroupBackground);
        rg.setOrientation(RadioGroup.HORIZONTAL);
        ViewGroup.LayoutParams rg_lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        rg.setLayoutParams(rg_lp);
//        if (mDividerDrawable !=null){
//            rg.setDividerDrawable(mDividerDrawable);
//        }else {
//            GradientDrawable drawable = new GradientDrawable();
//            drawable.setColor(mDividerColor);
//            drawable.setSize(mDividerPadding,ViewGroup.LayoutParams.WRAP_CONTENT);
//            rg.setDividerDrawable(drawable);
//        }
        rg.setShowDividers(RadioGroup.SHOW_DIVIDER_MIDDLE);
        rg.setDividerPadding(mDividerPadding);
        for (int i = 0; i < itemCount.size(); i++){
            RadioButton button = new RadioButton(context);
            button.setButtonDrawable(null);
            button.setGravity(Gravity.CENTER|Gravity.TOP);
            button.setTextColor(mTextColor);
            button.setLayoutParams(new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT,1f));
            button.setTextSize(mTextSize);
            button.setId(i);
            button.setPadding(0,70,0,0);
            if (contentDescriptions.size()>0){
                if (contentDescriptions.get(i)!=null){
                    button.setContentDescription(contentDescriptions.get(i));
                }
            }
            button.setOnFocusChangeListener(new View.OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (hasFocus){
                        if (v.getId()==0){
                            v.setNextFocusLeftId(0);
                        }else if (v.getId()==(itemCount.size()-1)){
                            v.setNextFocusRightId(itemCount.size()-1);
                        }
                        if (customRadioButtonFocus!=null){
                            customRadioButtonFocus.onRadioButtonFocus(getId(),v);
                        }
                    }
                }
            });
            Drawable topDrawable = null;
            if (select == i){
                if (isSelectThreeStyle){
                    if (i==0){
                        button.setBackgroundResource(leftSelectBg);
                    }else if (i==(itemCount.size()-1)){
                        button.setBackgroundResource(rightSelectBg);
                    }else {
                        button.setBackgroundResource(centerSelectBg);
                    }
                }else {
                    button.setBackgroundResource(radioButtonBackground);
                }
                button.setChecked(true);
                button.setTextColor(mTextSelectColor);
                if (hasImgRadioButton){
                    topDrawable = getResources().getDrawable(radioButtonSelectImg);
                }
            }else {
                if (hasImgRadioButton){
                    topDrawable = getResources().getDrawable(radioButtonImg);
                }
            }
            if (topDrawable!=null){
                topDrawable.setBounds(0,0,180,180);
                button.setCompoundDrawables(null,topDrawable,null,null);
            }
            button.setText(itemCount.get(i));
            radioButtons.add(button);
            rg.addView(button);
        }
        rg.setOnCheckedChangeListener(this);
        addView(rg);
    }

    public void setCustomRadioButtonChecked(int position) {
        setCustomRadioButtonChecked(position,true);
    }
    public void setCustomRadioButtonChecked(int position,boolean isFromUser) {
        if (position>=itemCount.size()|| position<0|| position==select){
            return;
        }
        select = position;
        for (int i = 0; i < itemCount.size(); i++) {
            RadioButton radioButton = radioButtons.get(i);
            Drawable topDrawable = null;
            if (position == i){
                radioButton.postOnAnimation(()->{
                    rg.setOnCheckedChangeListener(null);
                    radioButton.setChecked(true);
                    rg.setOnCheckedChangeListener(this);
                });
                radioButton.setTextColor(mTextSelectColor);
                if (isSelectThreeStyle){
                    if (i==0){
                        radioButton.setBackgroundResource(leftSelectBg);
                    }else if (i==(itemCount.size()-1)){
                        radioButton.setBackgroundResource(rightSelectBg);
                    }else {
                        radioButton.setBackgroundResource(centerSelectBg);
                    }
                }else {
                    radioButton.setBackgroundResource(radioButtonBackground);
                }
                if (hasImgRadioButton){
                    topDrawable = getResources().getDrawable(radioButtonSelectImg);
                }
            }else {
                radioButton.postOnAnimation(()->{
                    rg.setOnCheckedChangeListener(null);
                    radioButton.setChecked(false);
                    rg.setOnCheckedChangeListener(this);
                });
                radioButton.setBackgroundResource(0);
                radioButton.setTextColor(mTextColor);
                if (hasImgRadioButton){
                    topDrawable = getResources().getDrawable(radioButtonImg);
                }
            }
            if (topDrawable!=null){
                topDrawable.setBounds(0,0,180,180);
                radioButton.setCompoundDrawables(null,topDrawable,null,null);
            }

        }
    }
    public int getSelect(){
        return select;
    }
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        View viewById = group.findViewById(checkedId);
        if (select == checkedId){
            return;
        }
        setCustomRadioButtonChecked(checkedId,true);
        if (onCheckedChangeListener!=null){
            onCheckedChangeListener.onCheckedChanged(group,checkedId);
        }
        if (customRadioButtonSelect !=null){
            if(!viewById.isPressed() && !viewById.isFocused()){
                return;
            }
            customRadioButtonSelect.onRadioButtonSelect(getId(),checkedId);
        }
    }

    public void setCustomRadioButtonSelectListener(CustomRadioButtonSelect customRadioButtonSelect) {
        this.customRadioButtonSelect = customRadioButtonSelect;
    }

    public interface CustomRadioButtonSelect{
        void onRadioButtonSelect(int radioGroupId,int selectPosition);
    }
    public void setEnabled(boolean enabled) {
        for (RadioButton radioButton : radioButtons){
            radioButton.setEnabled(enabled);
        }
    }

    public void setRadioButtonFocusListener(CustomRadioButtonFocus customRadioButtonFocus) {
        this.customRadioButtonFocus = customRadioButtonFocus;
    }

    public interface CustomRadioButtonFocus{
        void onRadioButtonFocus(int radioGroupId,View v);
    }
}
